//导入模块
const fs = require('fs')
const path = require('path')
//封装提取css内容的方法
const getCssStr = data => {
  const regCss = /<style>([\s\S]*)<\/style>/
  const resCss = regCss.exec(data)
  // console.log(resCss[0])
  return resCss
}

//封装提取js内容的方法
const getJsStr = data => {
  const regJs = /<script>([\s\S]*)<\/script>/
  const resJs = regJs.exec(data)
  // console.log(resJs[1])
  return resJs
}

//读取index的内容
fs.readFile(path.join(__dirname, './素材/index.html'), 'utf-8', (err, dataStr) => {
  // err ? console.log(err) : console.log(dataStr)
  if (err) return console.log(err)

  // console.log(dataStr)
  //获取css内容,写入css文件
  const cssStr = getCssStr(dataStr)[1]
  fs.writeFile(path.join(__dirname, './clock/index.css'), cssStr, 'utf-8', err =>
    err ? console.log(err) : console.log('css写入成功')
  )

  //获取js内容,写入js文件
  const jsStr = getJsStr(dataStr)[1]
  fs.writeFile(path.join(__dirname, './clock/index.js'), jsStr, 'utf-8', err =>
    err ? console.log(err) : console.log('js写入成功')
  )

  //修改index.html中内容替换为引入,把修改后的内容写入html文件
  const htmlStr = dataStr
    .replace(getCssStr(dataStr)[0], '<link rel="stylesheet" href="./index.css">')
    .replace(getJsStr(dataStr)[0], '<script src="./index.js"></script>')
  // console.log(htmlStr)
  fs.writeFile(path.join(__dirname, './clock/index.html'), htmlStr, 'utf-8', err =>
    err ? console.log(err) : console.log('html写入成功')
  )
})
